package com.xw.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import static org.apache.poi.sl.draw.geom.GuideIf.Op.min;

/**
 * @Description: Redis缓存工具类
 * @Author: ASUS
 * @Date: 2024/12/19 09:15
 * @Version: 1.0
 */
@Component
public class RedisUtil {

    private final StringRedisTemplate redisTemplate;
    private final ObjectMapper objectMapper;

    @Autowired
    public RedisUtil(StringRedisTemplate redisTemplate, ObjectMapper objectMapper) {
        this.redisTemplate = redisTemplate;
        this.objectMapper = objectMapper;
    }



    // 删除缓存
    public void deleteCache(String key) {
        redisTemplate.delete(key);
    }

    // 设置缓存，支持对象类型
    public <T> void setCache(String key, T value) {
        try {
            String jsonValue = objectMapper.writeValueAsString(value);
            redisTemplate.opsForValue().set(key, jsonValue, 30, TimeUnit.MINUTES);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 获取缓存，支持对象类型
    public <T> T getCache(String key, Class<T> clazz) {
        String jsonValue = redisTemplate.opsForValue().get(key);
        try {
            if (jsonValue != null) {
                return objectMapper.readValue(jsonValue, clazz);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
